using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FreeSql.Internal.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Publicuse.Autofac;
using Publicuse.Cache;
using Publicuse.Entity;
using Publicuse.Entity;
using Publicuse.Entity.AttributeUtil;
using Publicuse.Export;
using Publicuse.Interface;
using Publicuse.Util;

namespace Publicuse.Appication
{
    /// <summary>
    /// 系统参数配置管理
    /// </summary>
    public class SpconfApplication
    {
        private static BaesApplication baseApplication;
        private static SpconfApplication userApplication;

        public static SpconfApplication GetApplication(ServiceContainer container)
        {
            baseApplication = new BaesApplication(container);
            return userApplication;
        }

        static SpconfApplication()
        {
            userApplication = new SpconfApplication();
        }

    /// <summary>
    /// 获取系统参数配置详细信息
    /// </summary>
    /// <param name="Id"></param>
    /// <returns></returns>
    public async Task<CommonResult> GetDetail(int Id)
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult();
                var list = baseApplication.mySqlSugar.QueryByExpression<Spconf>(
                    o => o.Id == Id,
                    out var msg
                );
                if (string.IsNullOrEmpty(msg) && list != null && list.Count > 0)
                {
                    var spconf = list.FirstOrDefault();
                    result.data = spconf;
                }
                result.msg = msg;
                return result;
            });
        }

        /// <summary>
        /// 获取系统参数配置信息列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<CommonResult> GetList(Spconf query)
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult();
                var tableName = TableAtributeUtil.GetTable<Spconf>();
                string sql = query.GetQueryString<Spconf>(null);
                SpconfQuery roleQuery = new SpconfQuery()
                {
                    tableName = tableName,
                    sqlWhere = sql,
                    sortFile = query.sortFile,
                    sortType = query.sortType,
                    files = query.files,
                    pageIndex = query.pageIndex,
                    pageSize = query.pageSize,
                };
                return baseApplication.GetList<Spconf>(roleQuery, false).GetAwaiter().GetResult();
            });
        }

        /// <summary>
        /// 获取系统登录页面信息
        /// </summary>
        /// <returns></returns>
        public async Task<CommonResult> GetIndexInfo()
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult();
                var msg = string.Empty;
                try
                {
                    var table = TableAtributeUtil.GetTable<Spconf>();
                    var sql =
                        $"select sValue from {table} where sCode in('loginsysremark','loginsysname');";
                    var list = baseApplication.mySqlSugar.Query<Spconf>(sql, out msg);
                    if (string.IsNullOrEmpty(msg) && list != null && list.Count > 0)
                    {
                        result.data = string.Join("|", list.Select(o => o.sValue));
                    }
                }
                catch (Exception ex)
                {
                    msg = ex.Message;
                }
                result.msg = msg;
                return result;
            });
        }

        /// <summary>
        /// 检查参数配置名称是否存在
        /// </summary>
        /// <param name="sName"></param>
        /// <param name="loginUserCode"></param>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<CommonResult> CheckName(
            string sName,
            string loginUserCode,
            string Id = ""
        )
        {
            return await baseApplication.CheckDataExists<Spconf>(
                BusinessType.spconf,
                BusinessLogType.writeLogToDataBase,
                o => o.sName == sName && o.status != -9,
                "检查参数配置名称是否存在",
                Id
            );
        }

    /// <summary>
    /// 检查参数配置编码是否存在
    /// </summary>
    /// <param name="sCode"></param>
    /// <param name="loginUserCode"></param>
    /// <param name="Id"></param>
    /// <returns></returns>
    public async Task<CommonResult> CheckCode(
        string sCode,
        string loginUserCode,
        string Id = ""
    )
    {
      return await baseApplication.CheckDataExists<Spconf>(
          BusinessType.spconf,
          BusinessLogType.writeLogToDataBase,
          o => o.sCode == sCode && o.status != -9,
          "检查参数配置编码是否存在",
          Id
      );
    }

    /// <summary>
    /// 新增修改系统参数配置信息
    /// </summary>
    /// <param name="info"></param>
    /// <returns></returns>
    public async Task<CommonResult> AddOrUpdate(Spconf info)
        {
            return await baseApplication.AddOrUpdate<Spconf>(
                info,
                BusinessType.spconf,
                BusinessLogType.writeLogToDataBase,
                null,
                o =>
                {
                    QueryCacheUtil<Spconf>.RemoveData(SpconfQuery.GetExportName);
                    DataCacheUtil.GetDataCacheUtil.RemoveData(TableAtributeUtil.GetTable<Spconf>());
                }
            );
        }

        /// <summary>
        /// 删除系统参数配置信息
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="loginUserCode"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public async Task<CommonResult> Delete(string Id, string loginUserCode, string type)
        {
            return await baseApplication.Delete<Spconf>(
                Id,
                loginUserCode,
                type,
                BusinessType.spconf,
                (autofaceInstance, baseService, data) =>
                {
                    CommonResult result = new CommonResult();
                    string msg = string.Empty;
                    Spconf info = new Spconf();
                    var newId = data.Id;
                    baseService.QueryInfoByID(Convert.ToInt32(newId), out msg, out info);
                    autofaceInstance.DoWork(
                        BusinessType.spconf,
                        BusinessActionType.delete,
                        null,
                        type + "Delete[" + info.sName + "]系统参数配置信息",
                        BusinessLogType.writeLogToDataBase,
                        (o) =>
                        {
                            if (!string.IsNullOrEmpty(info.sName))
                            {
                                List<string> initpar = new List<string>
                                {
                                    "SysVersion",
                                    "EveryDayInfo",
                                    "SysTimeOut",
                                    "RailwayName",
                                    "HighwayName",
                                    "CaptransportName",
                                    "WaterwayName",
                                    "PassengertransportTimer",
                                    "pwdretry",
                                    "loginretrytime",
                                    "previewpath"
                                };

                                if (initpar.Any(o => o.ToLower() == info.sName.ToLower()))
                                {
                                    result.code = (int)CodeResult.fail;
                                    result.msg = "该信息为系统初始化信息不能删除!";
                                }
                                else
                                {
                                    if (type == "-9")
                                    {
                                        var tableName = TableAtributeUtil.GetTable<Spconf>();
                                        string sql = $"update {tableName} set status=-9 where Id={newId}; ";
                                        Dictionary<string, string> pairsb = new Dictionary<
                                            string,
                                            string
                                        >()
                                        {
                                            { "Id", "" + info.Id + "" }
                                        };
                                        baseService.ExecuteSql(sql, pairsb, out msg);
                                    }
                                    else
                                    {
                                        baseService.Delete<Spconf>(
                                            info.Id.ToString().GetIntValue(),
                                            out msg
                                        );
                                    }
                                    if (string.IsNullOrEmpty(msg))
                                    {
                                        DataCacheUtil.GetDataCacheUtil.RemoveData(
                                            TableAtributeUtil.GetTable<Spconf>()
                                        );
                                        QueryCacheUtil<Spconf>.RemoveData(
                                            SpconfQuery.GetExportName
                                        );
                                        result.code = (int)CodeResult.success;
                                    }
                                }
                            }
                            else
                            {
                                result.msg = "[" + Id + "]系统参数配置信息不存在";
                            }
                            DataCacheUtil.GetDataCacheUtil.RemoveData(
                                TableAtributeUtil.GetTable<Spconf>()
                            );
                            QueryCacheUtil<Spconf>.RemoveData(SpconfQuery.GetExportName);
                            return result;
                        },
                        null,
                        ref result
                    );
                    return result.msg;
                }
            );
        }

        /// <summary>
        /// 还原系统参数配置信息
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="loginUserCode"></param>
        /// <returns></returns>
        public async Task<CommonResult> Reduction(string Id, string loginUserCode)
        {
            return await baseApplication.Reduction<Spconf>(
                Id,
                loginUserCode,
                BusinessType.spconf,
                (a, b, info) =>
                {
                    return info.sName;
                },
                (o, info) =>
                {
                    DataCacheUtil.GetDataCacheUtil.RemoveData(TableAtributeUtil.GetTable<Spconf>());
                }
            );
        }
    }
}
